/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.utils

import cool.taomu.software.fig.configure.ConfigureManage
import cool.taomu.software.fig.configure.entity.ConfigureEntity.Host
import java.io.IOException
import java.net.InetAddress
import org.apache.commons.net.ntp.NTPUDPClient
import org.slf4j.LoggerFactory

import static cool.taomu.software.fig.configure.ConfigureManage.*

class NTPUnixTimestamp {
    val static LOG = LoggerFactory.getLogger(NTPUnixTimestamp);
    var static Host HOST = null;

    new() {
        if (HOST === null) {
            HOST = ConfigureManage.loadConfig.ntp;
        }
    }

    def unixTimestamp() {
        try {
            if (HOST !== null && !HOST.ip.equals("None")) {
                LOG.info("get ntp current time millis");
                var ntpUdpClient = new NTPUDPClient();
                var inetAddress = InetAddress.getByName(HOST.ip);
                ntpUdpClient.setDefaultTimeout(500);
                var timeInfo = ntpUdpClient.getTime(inetAddress, HOST.port);
                return timeInfo.getMessage().getOriginateTimeStamp().getTime() / 1000;
            }
        }catch(IOException ex){
           LOG.error("NTP Error:{}",ex.message);
        }
        LOG.info("get local current time millis");
        return System.currentTimeMillis() / 1000;
    }

    def static void main(String[] args) {
        ConfigureManage.configPath = "/home/rcmu/workspace/fig/fig-configure/src/main/resources/fig.yml";
        println(new NTPUnixTimestamp().unixTimestamp)
    }

}
